package com.example.its2021606134chh.DMVModule;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.example.its2021606134chh.ETCModule.ETC_Car_Balance;
import com.example.its2021606134chh.ETCModule.ETC_Car_Recharge;
import com.example.its2021606134chh.ETCModule.MySQLiteOpenHelper;
import com.example.its2021606134chh.HttpUtil;
import com.example.its2021606134chh.MainActivity;
import com.example.its2021606134chh.R;
import com.example.its2021606134chh.fragment.IndexFragment;
import com.example.its2021606134chh.fragment.PrepaidRecordsFragment;
import com.google.gson.Gson;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link DMV_account_managementFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class DMV_account_managementFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "title";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private ImageView imgDMVCar1;
    private TextView tvDMVCarNum1;
    private TextView tvDMVCarUser1;
    private TextView tvDMVCarBalance1;
    private CheckBox cheDMVCar1;
    private Button btnDMVCarRecharge1;
    private ImageView imgDMVCar2;
    private TextView tvDMVCarNum2;
    private TextView tvDMVCarUser2;
    private TextView tvDMVCarBalance2;
    private CheckBox cheDMVCar2;
    private Button btnDMVCarRecharge2;
    private ImageView imgDMVCar3;
    private TextView tvDMVCarNum3;
    private TextView tvDMVCarUser3;
    private TextView tvDMVCarBalance3;
    private CheckBox cheDMVCar3;
    private Button btnDMVCarRecharge3;
    private ImageView imgDMVCar4;
    private TextView tvDMVCarNum4;
    private TextView tvDMVCarUser4;
    private TextView tvDMVCarBalance4;
    private CheckBox cheDMVCar4;
    private Button btnDMVCarRecharge4;
    private TextView tvDMVBatchRecharge, tvDMVRechargeRecord;
    private LinearLayout DMVLayout1, DMVLayout2, DMVLayout3, DMVLayout4;
    private int BalAlaNum;
    private int[] carList = {1, 2, 3, 4};   //车辆列表
    private static final int CAR1 = 1;
    private static final int CAR2 = 2;
    private static final int CAR3 = 3;
    private static final int CAR4 = 4;
    private static final int waringColor = R.color.colorWaring;
    private static final int normalColor = R.color.white;
    private int carBalance1;
    private int carBalance2;
    private int carBalance3;
    private int carBalance4;
    private String checkMsg;
    MySQLiteOpenHelper openHelper;
    SQLiteDatabase database;

    public DMV_account_managementFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment DMV_account_managementFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static DMV_account_managementFragment newInstance(String param1, String param2) {
        DMV_account_managementFragment fragment = new DMV_account_managementFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_d_m_v_account_management, container, false);
        tvDMVRechargeRecord = (TextView) view.findViewById(R.id.tvDMVRechargeRecord);
        tvDMVBatchRecharge = (TextView) view.findViewById(R.id.tvDMVBatchRecharge);
        imgDMVCar1 = (ImageView) view.findViewById(R.id.imgDMVCar1);
        tvDMVCarNum1 = (TextView) view.findViewById(R.id.tvDMVCarNum1);
        tvDMVCarUser1 = (TextView) view.findViewById(R.id.tvDMVCarUser1);
        tvDMVCarBalance1 = (TextView) view.findViewById(R.id.tvDMVCarBalance1);
        cheDMVCar1 = (CheckBox) view.findViewById(R.id.cheDMVCar1);
        btnDMVCarRecharge1 = (Button) view.findViewById(R.id.btnDMVCarRecharge1);
        imgDMVCar2 = (ImageView) view.findViewById(R.id.imgDMVCar2);
        tvDMVCarNum2 = (TextView) view.findViewById(R.id.tvDMVCarNum2);
        tvDMVCarUser2 = (TextView) view.findViewById(R.id.tvDMVCarUser2);
        tvDMVCarBalance2 = (TextView) view.findViewById(R.id.tvDMVCarBalance2);
        cheDMVCar2 = (CheckBox) view.findViewById(R.id.cheDMVCar2);
        btnDMVCarRecharge2 = (Button) view.findViewById(R.id.btnDMVCarRecharge2);
        imgDMVCar3 = (ImageView) view.findViewById(R.id.imgDMVCar3);
        tvDMVCarNum3 = (TextView) view.findViewById(R.id.tvDMVCarNum3);
        tvDMVCarUser3 = (TextView) view.findViewById(R.id.tvDMVCarUser3);
        tvDMVCarBalance3 = (TextView) view.findViewById(R.id.tvDMVCarBalance3);
        cheDMVCar3 = (CheckBox) view.findViewById(R.id.cheDMVCar3);
        btnDMVCarRecharge3 = (Button) view.findViewById(R.id.btnDMVCarRecharge3);
        imgDMVCar4 = (ImageView) view.findViewById(R.id.imgDMVCar4);
        tvDMVCarNum4 = (TextView) view.findViewById(R.id.tvDMVCarNum4);
        tvDMVCarUser4 = (TextView) view.findViewById(R.id.tvDMVCarUser4);
        tvDMVCarBalance4 = (TextView) view.findViewById(R.id.tvDMVCarBalance4);
        cheDMVCar4 = (CheckBox) view.findViewById(R.id.cheDMVCar4);
        btnDMVCarRecharge4 = (Button) view.findViewById(R.id.btnDMVCarRecharge4);
        DMVLayout1 = (LinearLayout) view.findViewById(R.id.DMVLayout1);
        DMVLayout2 = (LinearLayout) view.findViewById(R.id.DMVLayout2);
        DMVLayout3 = (LinearLayout) view.findViewById(R.id.DMVLayout3);
        DMVLayout4 = (LinearLayout) view.findViewById(R.id.DMVLayout4);
        //        从SharedPreferences取出告警阈值
        SharedPreferences sp = getActivity().getSharedPreferences("balance_alarm", Activity.MODE_PRIVATE);
        if (sp != null) {
            BalAlaNum = sp.getInt("BalAlaNum", 0);
        }
        getBalance();
        //                取得当前时间
        Date dNow = new Date();
        SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");
        String sNow = ft.format(dNow);

        tvDMVRechargeRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), MainActivity.class);
                intent.putExtra("DMV", 1);
                intent.putExtra("Recharge", true);
                startActivity(intent);
            }
        });

        btnDMVCarRecharge1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cheDMVCar1.setChecked(true);
                getCheck();
                dialogueBox(CAR1, carBalance1, sNow, checkMsg);
            }
        });
        btnDMVCarRecharge2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cheDMVCar2.setChecked(true);
                getCheck();
                dialogueBox(CAR2, carBalance2, sNow, checkMsg);
            }
        });
        btnDMVCarRecharge3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cheDMVCar3.setChecked(true);
                getCheck();
                dialogueBox(CAR3, carBalance3, sNow, checkMsg);
            }
        });

        btnDMVCarRecharge4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cheDMVCar4.setChecked(true);
                getCheck();
                dialogueBox(CAR4, carBalance4, sNow, checkMsg);
            }
        });

        tvDMVBatchRecharge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<Integer> carCheList = new ArrayList<Integer>();
                if (cheDMVCar1.isChecked()) {
                    carCheList.add(1);
                }
                if (cheDMVCar2.isChecked()) {
                    carCheList.add(2);
                }
                if (cheDMVCar3.isChecked()) {
                    carCheList.add(3);
                }
                if (cheDMVCar4.isChecked()) {
                    carCheList.add(4);
                }
                getCheck();
                AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
                View view = LayoutInflater.from(Objects.requireNonNull(getActivity()).getBaseContext()).inflate(R.layout.activity_dmv_account_dialog,null,false);
                dialog.setView(view);
                TextView tvDMVDialogCarNum = (TextView)view.findViewById(R.id.tvDMVDialogCarNum);
                Button btnDMVRechargeSave = (Button)view.findViewById(R.id.btnDMVRechargeSave);
                EditText edtDMVRechargeNum = (EditText)view.findViewById(R.id.edtDMVRechargeNum);
                Button btnDMVRechargeCancel = (Button)view.findViewById(R.id.btnDMVRechargeCancel);
                AlertDialog mdialog = dialog.show();
                tvDMVDialogCarNum.setText(checkMsg.trim());
                btnDMVRechargeSave.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                取得充值金额
                        String sRecharge = edtDMVRechargeNum.getText().toString();
                        int rechargeNum = Integer.parseInt(sRecharge);
//                判断1到999的整数
                        if (rechargeNum >= 1 && rechargeNum <= 999) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    for (int carID : carCheList) {
                                        HttpUtil.asyncRequest(new HttpUtil.AsyncCallBack() {
                                            @Override
                                            public void onFailure(Exception e) {

                                            }

                                            @Override
                                            public void onResponse(String json) {
                                                String msg = "";
                                                int carBalance = 0;
                                                if (carID == CAR1) {
                                                    carBalance = carBalance1;
                                                } else if (carID == CAR2) {
                                                    carBalance = carBalance2;
                                                } else if (carID == CAR3) {
                                                    carBalance = carBalance3;
                                                } else if (carID == CAR4) {
                                                    carBalance = carBalance4;
                                                }
                                                Gson gson = new Gson();
                                                ETC_Car_Recharge car_recharge = gson.fromJson(json, ETC_Car_Recharge.class);
                                                String RESULT = car_recharge.getRESULT();
                                                if (RESULT.equals("S")) {
//                                        向数据库传入数据
                                                    ContentValues values = new ContentValues();
                                                    values.put("carID", carID);
                                                    values.put("carBalance", carBalance + rechargeNum);
                                                    values.put("carRecharge",rechargeNum);
                                                    values.put("user", "user1");
                                                    values.put("time", sNow);
                                                    openHelper = new MySQLiteOpenHelper(getContext(), "ETCaccount1.db", null, 1);
                                                    database = openHelper.getWritableDatabase();
                                                    database.insert("etccar", null, values);
                                                    database.close();
                                                    mdialog.dismiss();
                                                    getBalance();
                                                    msg = carID + "号小车充值" + rechargeNum + "元成功";
                                                    Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                                                } else {
                                                    mdialog.dismiss();
                                                    msg = carID + "号小车充值失败";
                                                    Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                                                }
                                            }
                                        }, "set_car_account_recharge", new String[]{"CarId", "Money", "UserName"}, carID, rechargeNum, "user1");
                                    }
                                }
                            }).start();
                        } else {
                            Toast.makeText(getActivity(), "只能输入1到999之间的整数", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

                btnDMVRechargeCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        cheDMVCar1.setChecked(false);
                        cheDMVCar2.setChecked(false);
                        cheDMVCar3.setChecked(false);
                        cheDMVCar4.setChecked(false);
                        mdialog.dismiss();
                    }
                });
            }
        });

        return view;
    }

    private void getBalance() {
        for (int carId : carList) {
            HttpUtil.asyncRequest(new HttpUtil.AsyncCallBack() {
                @Override
                public void onFailure(Exception e) {

                }

                @Override
                public void onResponse(String json) {
                    Log.i("TAG", json);
                    Gson gson = new Gson();
                    ETC_Car_Balance carBalance = gson.fromJson(json, ETC_Car_Balance.class);
                    int iCarBal = carBalance.getBalance();
                    String sCarBal = "余额：" + carBalance.getBalance() + "元";

//                            根据车号设置阈值提示
                    if (carId == CAR1) {
                        if (iCarBal < BalAlaNum) {
                            DMVLayout1.setBackground(getResources().getDrawable(waringColor));
                        } else {
                            DMVLayout1.setBackground(getResources().getDrawable(normalColor));
                        }
                        tvDMVCarBalance1.setText(sCarBal);
                        carBalance1 = iCarBal;
                    } else if (carId == CAR2) {
                        if (iCarBal < BalAlaNum) {
                            DMVLayout2.setBackground(getResources().getDrawable(waringColor));
                        } else {
                            DMVLayout2.setBackground(getResources().getDrawable(normalColor));
                        }
                        tvDMVCarBalance2.setText(sCarBal);
                        carBalance2 = iCarBal;
                    } else if (carId == CAR3) {
                        if (iCarBal < BalAlaNum) {
                            DMVLayout3.setBackground(getResources().getDrawable(waringColor));
                        } else {
                            DMVLayout3.setBackground(getResources().getDrawable(normalColor));
                        }
                        tvDMVCarBalance3.setText(sCarBal);
                        carBalance3 = iCarBal;
                    } else if (carId == CAR4) {
                        if (iCarBal < BalAlaNum) {
                            DMVLayout4.setBackground(getResources().getDrawable(waringColor));
                        } else {
                            DMVLayout4.setBackground(getResources().getDrawable(normalColor));
                        }
                        tvDMVCarBalance4.setText(sCarBal);
                        carBalance4 = iCarBal;
                    }
                }
            }, "get_car_account_balance", new String[]{"CarId", "UserName"}, carId, "user1");
        }
    }

    private void getCheck() {
        checkMsg = "";
        if (cheDMVCar1.isChecked()) {
            checkMsg += " " + "辽A10001";
        }
        if (cheDMVCar2.isChecked()) {
            checkMsg += " " + "辽A10002";
        }
        if (cheDMVCar3.isChecked()) {
            checkMsg += " " + "辽A10003";
        }
        if (cheDMVCar4.isChecked()) {
            checkMsg += " " + "辽A10004";
        }
    }

    private void dialogueBox(int carID, int carBalance, String time, String checkMsg) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
        View view = LayoutInflater.from(Objects.requireNonNull(getActivity()).getBaseContext()).inflate(R.layout.activity_dmv_account_dialog,null,false);
        dialog.setView(view);
        TextView tvDMVDialogCarNum = (TextView)view.findViewById(R.id.tvDMVDialogCarNum);
        Button btnDMVRechargeSave = (Button)view.findViewById(R.id.btnDMVRechargeSave);
        EditText edtDMVRechargeNum = (EditText)view.findViewById(R.id.edtDMVRechargeNum);
        Button btnDMVRechargeCancel = (Button)view.findViewById(R.id.btnDMVRechargeCancel);
        AlertDialog mdialog = dialog.show();
        tvDMVDialogCarNum.setText(checkMsg.trim());
        btnDMVRechargeSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                取得充值金额
                String sRecharge = edtDMVRechargeNum.getText().toString();
                int rechargeNum = Integer.parseInt(sRecharge);
//                判断1到999的整数
                if (rechargeNum >= 1 &&  rechargeNum <= 999) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            HttpUtil.asyncRequest(new HttpUtil.AsyncCallBack() {
                                @Override
                                public void onFailure(Exception e) {

                                }

                                @Override
                                public void onResponse(String json) {
                                    String msg = "";
                                    Log.i("TAG", json);
                                    Gson gson = new Gson();
                                    ETC_Car_Recharge car_recharge = gson.fromJson(json, ETC_Car_Recharge.class);
                                    String RESULT = car_recharge.getRESULT();
                                    if (RESULT.equals("S")) {
//                                        向数据库传入数据
                                        ContentValues values = new ContentValues();
                                        values.put("carID", carID);
                                        values.put("carBalance", carBalance + rechargeNum);
                                        values.put("carRecharge",rechargeNum);
                                        values.put("user", "user1");
                                        values.put("time", time);
                                        openHelper = new MySQLiteOpenHelper(getContext(), "ETCaccount1.db", null, 1);
                                        database = openHelper.getWritableDatabase();
                                        database.insert("etccar", null, values);
                                        database.close();
                                        mdialog.dismiss();
                                        getBalance();
                                        msg = carID + "号小车充值" + rechargeNum + "元成功";
                                        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                                    } else {
                                        mdialog.dismiss();
                                        msg = carID + "号小车充值失败";
                                        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                                    }
                                }
                            }, "set_car_account_recharge", new String[]{"CarId", "Money", "UserName"}, carID, rechargeNum, "user1");
                        }
                    }).start();
                } else {
                    Toast.makeText(getActivity(), "只能输入1到999之间的整数", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btnDMVRechargeCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cheDMVCar1.setChecked(false);
                cheDMVCar2.setChecked(false);
                cheDMVCar3.setChecked(false);
                cheDMVCar4.setChecked(false);
                mdialog.dismiss();
            }
        });
    }

}